// cloud/functions/register/index.js
const cloud = require('wx-server-sdk');

cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV });
const db = cloud.database();

exports.main = async (event, context) => {
  const { account, password, stdId, avatarFileID } = event;
  if (!account || !password || !stdId) {
    return { code: 400, message: '账号、密码和学号不能为空' };
  }

  try {
    // 检查账号是否已存在
    const userRes = await db.collection('users').where({ account }).get();
    if (userRes.data.length > 0) {
      return { code: 1, message: '账号已存在' };
    }

    // 检查学号是否已绑定
    const stdRes = await db.collection('users').where({ stdId }).get();
    if (stdRes.data.length > 0) {
      return { code: 2, message: '学号已被绑定' };
    }

    // 创建新用户（头像FileID若未上传则为空字符串）
    const now = db.serverDate();
    const userData = {
      account,
      password, // 实际项目中应存储加密后的密码（如md5）
      stdId,
      avatarFileID: avatarFileID || '',
      createTime: now,
      updateTime: now
    };

    await db.collection('users').add({ data: userData });
    return { code: 0, message: '注册成功' };
  } catch (error) {
    console.error('注册失败:', error);
    return { code: 500, message: '服务器异常' };
  }
};